package com.vertx.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.EventBus;

/**
 * @name: MyVerticle
 * @description: MyVerticle
 * @author: jiangcs
 */
public class MyVerticle extends AbstractVerticle {
    @Override
    public void start() throws Exception {
        try {
            vertx.createHttpServer()
                    .requestHandler(req -> {
                        req.response()
                                .putHeader("Content-Type", "text/plain")
                                .end("My: Hello World!");
                    }).listen(8080);

            EventBus eventBus = vertx.eventBus();
            // 订阅消息
            eventBus.consumer("vertx.learning", (msg) -> {
                System.out.println("consumer1: " + msg.body());

                // 回复确认
                msg.reply("confirm ok");
            });
            eventBus.consumer("vertx.learning", (msg) -> {
                System.out.println("consumer2: " + msg.body());

                // 回复确认
                msg.reply("confirm ok");
            });
            // 发布消息
            DeliveryOptions deliveryOptions = new DeliveryOptions();
            deliveryOptions.addHeader("self-header", "vert.x");
            eventBus.publish("vertx.learning", "i am coming!", deliveryOptions);

            // 发送消息
            eventBus.send("vertx.learning", "i am come");
            eventBus.request("vertx.learning", "i am come 2", (asyncResult) -> {
                System.out.println("request receive: " + asyncResult.result().body());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
